import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  const loginUser = store.state.user.loginUser;
  if (!loginUser || !loginUser.userRole) {
    await store.dispatch("user/getLoginUser");
  }
  const needAccess = to.meta?.access ?? ACCESS_ENUM.GUEST;

  // 符合
  if (checkAccess(loginUser, needAccess as string)) {
    next();
    return;
  }
  // 不符合，未登录，继续登录
  else if (!loginUser || !loginUser.userRole) {
    next(`/user/login?redirect=${to.fullPath}`);
    return;
  }
  // 不符合，已登录，跳到错误页
  else {
    next(`/noAuth`);
  }
  next();
});
